import 'dart:convert';

import 'package:airbnb_clone/internal/http/dao/get_self_dao.dart';
import 'package:airbnb_clone/internal/http/dao/get_user_info_dao.dart';
import 'package:airbnb_clone/internal/sqlite/dao/message_dao.dart';
import 'package:airbnb_clone/internal/ws/core/wsconnect.dart';
import 'package:airbnb_clone/models/user_message.dart';
import 'package:airbnb_clone/widgets/chat_detail_view/chat_body.dart';
import 'package:flutter/material.dart';

import '../../components/dialog/msg_dialog.dart';
import '../../constant/constant.dart';
import '../../models/response.dart';

// ignore: must_be_immutable
class ChatDetailPage extends StatefulWidget {
  int userId;

  ChatDetailPage({required this.userId, super.key});

  @override
  State<ChatDetailPage> createState() => _ChatDetailPageState();
}

class _ChatDetailPageState extends State<ChatDetailPage> {
  String _userName = "获取失败";
  String selfName = "";
  final List<UserMessage> _messageList = [];
  String _inputMeassageField = "";
  final TextEditingController _inputMessageController = TextEditingController();
  late WebSocketMangeer _webSocketMangeer;
  late int selfId = 0;
  // 页面初始化
  @override
  void initState() {
    super.initState();
    // 加载数据
    _loadUserData();
    // 初始化聊天
    initWsConnect();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.sizeOf(context);
    return Material(
      child: Scaffold(
        body: Container(
          height: size.height,
          decoration:
              BoxDecoration(gradient: LinearGradient(colors: bgGradientColor)),
          child: SingleChildScrollView(
              child: Column(
            children: [
              SizedBox(
                height: size.height * 0.1,
                child: buildTopBar(context, _userName),
              ),
              Container(
                margin: const EdgeInsets.only(top: 8),
                color: bgColor,
                height: size.height * 0.79,
                child: ChatBody(
                  messageList: _messageList,
                  friendId: widget.userId,
                  selfId: widget.userId,
                ),
              ),
              Container(
                // 由输入框决定
                // height: size.height * 0.1,
                color: Colors.white,
                child: buildMessageSendTextField(context),
              )
            ],
          )),
        ),
      ),
    );
  }

  // 顶部
  Widget buildTopBar(BuildContext context, String userName) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8),
      decoration:
          BoxDecoration(gradient: LinearGradient(colors: topBarBgColor)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          IconButton(
            icon: const Icon(Icons.arrow_back),
            onPressed: () {
              // context.pop();
              Navigator.of(context).pop(false);
            },
          ),
          Text(
            userName == "" ? " 用户名未设置" : userName,
            style: TextStyle(
                decorationColor: Colors.white.withOpacity(0),
                textBaseline: TextBaseline.alphabetic,
                color: Colors.black,
                fontSize: 24,
                fontWeight: FontWeight.w500),
          ),
          const Icon(Icons.ios_share_sharp)
        ],
      ),
    );
  }

  // 主体
  Widget buildChatBody() {
    return ConstrainedBox(
      constraints: const BoxConstraints(
        maxWidth: 200.0,
      ),
    );
  }

  // 消息输入框
  Widget buildMessageSendTextField(BuildContext context) {
    final size = MediaQuery.sizeOf(context);
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Expanded(child: Container()),
        Container(
          padding: const EdgeInsets.all(8),
          width: size.width * 0.8,
          constraints: BoxConstraints(
              minHeight: size.height * 0.1, maxHeight: size.height * 0.4),
          child: TextField(
            controller: _inputMessageController,
            maxLines: null,
            maxLength: 200,
            decoration: InputDecoration(
                filled: true,
                fillColor: Colors.grey[200],
                border: OutlineInputBorder(
                  borderSide: BorderSide.none,
                  borderRadius: BorderRadius.circular(7),
                ),
                hintText: '',
                counterText: ''),
            onTap: () {
              setState(() {});
            },
          ),
        ),
        TextButton(
            style: ButtonStyle(
                shape: MaterialStateProperty.all(RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8))),
                overlayColor: MaterialStateProperty.resolveWith((states) {
                  return const Color.fromARGB(120, 124, 120, 120);
                })),
            // 发送消息
            onPressed: () {
              FocusScope.of(context).unfocus();

              _inputMeassageField = _inputMessageController.text;
              _inputMessageController.clear();
              _sendMessage();
            },
            child: const Text(
              "发送",
              style: TextStyle(color: Colors.black),
            ))
      ],
    );
  }

  // 加载用户数据
  Future<void> _loadUserData() async {
    // 加载用户名
    TiebaResponse response = await GetUserInfoDao.get(widget.userId);
    if (response.code == 200) {
      if (mounted) {
        setState(() {
          _userName = response.result["name"];
        });
      }
    } else {
      // ignore: use_build_context_synchronously
      MsgDialog.msgDialog(context, response.msg);
    }
    // 获取自身信息
    TiebaResponse response2 = await GetSelfInfoDao.get();
    if (response2.code == 200) {
      if (mounted) {
        setState(() {
          selfId = response2.result["id"];
          selfName = response2.result["username"];
          // 加载聊天数据
          _loadMessageList();
        });
      }
    } else {
      // ignore: use_build_context_synchronously
      MsgDialog.msgDialog(context, response2.msg);
    }
  }

  // 加载聊天记录
  void _loadMessageList() async {
    // 加载聊天记录
    List<UserMessage> messageList =
        await MessageDao().getAllData(widget.userId, selfId);
    if (mounted) {
      setState(() {
        _messageList.clear();
        _messageList.addAll(messageList);
      });
    }
  }

  // 初始化wsocket
  void initWsConnect() {
    _webSocketMangeer = WebSocketMangeer(
        handFunctoin: _handFunction, listenFunction: _listenFunction);
  }

  // 发送消息
  Future<void> _sendMessage() async {
    _webSocketMangeer.sendMessage(widget.userId, _inputMeassageField);
    await MessageDao().insertData(UserMessage(
        id: 0,
        senderId: selfId,
        receptorId: widget.userId,
        userName: selfName,
        userImg: "userImg",
        context: _inputMeassageField,
        createTime: DateTime.now()));
    if (mounted) {
      setState(() {
        _loadMessageList();
      });
    }
  }

  // 关闭连接
  @override
  void dispose() {
    _webSocketMangeer.closeConnect();
    super.dispose();
  }

  // ws连接处理
  Future<void> _handFunction(dynamic data) async {
    var jsonData = jsonDecode(data);
    await MessageDao().insertData(UserMessage(
        id: 0,
        senderId: jsonData["Sender"],
        receptorId: jsonData["Receptor"],
        userName: "userName",
        userImg: "userImg",
        context: jsonData["Msg"],
        createTime: DateTime.now()));
    if (mounted) {
      setState(() {
        _loadMessageList();
      });
    }
  }

  // ws状态监听
  void _listenFunction(dynamic data) {}
}
